/**
 * 简化版代理服务器，在MCP服务不可用时提供模拟数据
 */
const express = require('express');
const cors = require('cors');
const mysql = require('mysql2/promise');
const http = require('http');
const https = require('https');
const { URL } = require('url');
const fetch = require('node-fetch');

const app = express();
const PORT = 3001;

// 允许跨域请求
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// MySQL数据库配置
const dbConfig = {
  host: '127.0.0.1',
  port: 3306,
  user: 'root',
  password: 'Z159v677',
  database: 'demostore'
};

// MySQL数据库连接
let mysqlPool;
try {
  // 尝试建立连接池
  console.log("尝试连接数据库...");
  mysqlPool = mysql.createPool({
    host: dbConfig.host,
    port: dbConfig.port,
    user: dbConfig.user,
    password: dbConfig.password,
    database: dbConfig.database,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
  });
  console.log("数据库连接池已创建");
} catch (error) {
  console.error("MySQL连接池创建失败:", error);
}

// 添加数据库健康检查路由 - 用于前端检测数据库连接状态
app.get('/api/health-check', async (req, res) => {
  try {
    if (!mysqlPool) {
      return res.status(500).json({ status: 'error', message: '数据库连接池未初始化' });
    }
    
    // 尝试从连接池获取连接并执行简单查询
    const connection = await mysqlPool.getConnection();
    const [result] = await connection.execute('SELECT 1 as healthCheck');
    connection.release();
    
    if (result && result.length > 0) {
      return res.json({ status: 'ok', message: '数据库连接正常', data: result[0] });
    } else {
      return res.status(500).json({ status: 'error', message: '无法执行健康检查查询' });
    }
  } catch (error) {
    console.error('数据库健康检查失败:', error);
    return res.status(500).json({ status: 'error', message: '数据库连接失败', error: error.message });
  }
});

// 前端健康检查路由 - 用于确认服务器是否在线
app.get('/health-check', async (req, res) => {
  res.json({ status: 'ok', message: '服务器运行正常' });
});

// 数据库查询接口 - 供前端API请求使用
app.post('/api/db/query', async (req, res) => {
  try {
    if (!mysqlPool) {
      return res.status(500).json({ error: '数据库连接池未初始化' });
    }
    
    const { sql, params } = req.body;
    if (!sql) {
      return res.status(400).json({ error: '缺少SQL参数' });
    }
    
    // 检查SQL是否安全（简单检查，生产环境应有更严格措施）
    const disallowedKeywords = ['DROP', 'TRUNCATE', 'DELETE FROM', 'UPDATE', 'INSERT INTO'];
    const isQueryAllowed = !disallowedKeywords.some(keyword => 
      sql.toUpperCase().includes(keyword) && !req.headers['x-allow-write']
    );
    
    if (!isQueryAllowed) {
      return res.status(403).json({ error: '不允许执行此类SQL语句' });
    }
    
    // 执行查询
    console.log('执行SQL查询:', sql, params || []);
    const connection = await mysqlPool.getConnection();
    const [results] = await connection.execute(sql, params || []);
    connection.release();
    
    // 返回结果
    console.log('查询结果:', results);
    return res.json(results);
  } catch (error) {
    console.error('数据库查询错误:', error);
    return res.status(500).json({ error: error.message });
  }
});

// 添加中间件，拦截所有响应，确保交通方式选项中不包含"火车"
app.use((req, res, next) => {
  const originalSend = res.send;
  const originalJson = res.json;
  
  // 拦截send方法
  res.send = function(body) {
    // 只处理字符串和可能的JSON响应
    if (typeof body === 'string') {
      try {
        // 尝试解析JSON
        const data = JSON.parse(body);
        
        // 递归检查并清理对象中所有含"火车"的选项
        const cleanObject = (obj) => {
          if (!obj || typeof obj !== 'object') return obj;
          
          // 清理数组
          if (Array.isArray(obj)) {
            // 过滤掉label为"火车"的项目
            return obj.filter(item => !(item && item.label === '火车')).map(cleanObject);
          }
          
          // 清理对象
          const result = {};
          for (const key in obj) {
            // 如果值是"火车"并且键名看起来像label，跳过
            if (obj[key] === '火车' && key.toLowerCase().includes('label')) continue;
            result[key] = cleanObject(obj[key]);
          }
          return result;
        };
        
        const cleanData = cleanObject(data);
        body = JSON.stringify(cleanData);
      } catch (e) {
        // 不是JSON，检查是否包含火车字符串
        if (body.includes('"label":"火车"') || body.includes('"label":"Train"')) {
          body = body.replace(/"label":"火车"/g, '"label":"公共交通"')
                     .replace(/"label":"Train"/g, '"label":"Public Transit"');
        }
      }
    }
    
    return originalSend.call(this, body);
  };
  
  // 拦截json方法
  res.json = function(obj) {
    // 递归处理对象
    const cleanObject = (obj) => {
      if (!obj || typeof obj !== 'object') return obj;
      
      if (Array.isArray(obj)) {
        return obj.filter(item => !(item && item.label === '火车')).map(cleanObject);
      }
      
      const result = {};
      for (const key in obj) {
        if (obj[key] === '火车' && key.toLowerCase().includes('label')) continue;
        result[key] = cleanObject(obj[key]);
      }
      return result;
    };
    
    return originalJson.call(this, cleanObject(obj));
  };
  
  next();
});

// 高德地图API代理 - 地址转坐标
app.get('/amap/maps/geo', async (req, res) => {
  const { address, city } = req.query;
  const key = '4449ac26963227ad33708de521f024c5'; // 高德地图Web服务API的key
  
  console.log(`地理编码请求: 地址=${address}, 城市=${city || '未指定'}`);
  
  const apiUrl = new URL('https://restapi.amap.com/v3/geocode/geo');
  apiUrl.searchParams.set('key', key);
  apiUrl.searchParams.set('address', address);
  if (city) {
    apiUrl.searchParams.set('city', city);
  }
  
  console.log(`发送请求到高德地图: ${apiUrl.toString()}`);
  
  try {
    // 直接使用fetch进行请求，不使用fetchAMapAPI函数
    const response = await fetch(apiUrl.toString());
    
    if (!response.ok) {
      console.error(`高德地图API请求失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({ 
        error: `API请求失败: ${response.status} ${response.statusText}` 
      });
    }
    
    const contentType = response.headers.get('content-type');
    console.log(`响应内容类型: ${contentType}`);
    
    const data = await response.json();
    console.log(`地理编码响应: status=${data.status}, info=${data.info}, 找到地点数=${data.count || 0}`);
    
    res.json(data);
  } catch (error) {
    console.error('高德地图API请求错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 高德地图API代理 - 驾车路线规划
app.get('/amap/maps/direction_driving', async (req, res) => {
  const { origin, destination } = req.query;
  const key = '4449ac26963227ad33708de521f024c5';
  
  console.log(`驾车路线规划请求: 起点=${origin}, 终点=${destination}`);
  
  const apiUrl = new URL('https://restapi.amap.com/v3/direction/driving');
  apiUrl.searchParams.set('key', key);
  apiUrl.searchParams.set('origin', origin);
  apiUrl.searchParams.set('destination', destination);
  apiUrl.searchParams.set('extensions', 'all');
  
  console.log(`发送请求到高德地图: ${apiUrl.toString()}`);
  
  try {
    const response = await fetch(apiUrl.toString());
    
    if (!response.ok) {
      console.error(`高德地图API请求失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({ 
        error: `API请求失败: ${response.status} ${response.statusText}` 
      });
    }
    
    const data = await response.json();
    console.log(`驾车路线规划响应: status=${data.status}, info=${data.info}`);
    
    res.json(data);
  } catch (error) {
    console.error('高德地图API请求错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 高德地图API代理 - 步行路线规划
app.get('/amap/maps/direction_walking', async (req, res) => {
  const { origin, destination } = req.query;
  const key = '4449ac26963227ad33708de521f024c5';
  
  console.log(`步行路线规划请求: 起点=${origin}, 终点=${destination}`);
  
  const apiUrl = new URL('https://restapi.amap.com/v3/direction/walking');
  apiUrl.searchParams.set('key', key);
  apiUrl.searchParams.set('origin', origin);
  apiUrl.searchParams.set('destination', destination);
  apiUrl.searchParams.set('extensions', 'all');
  
  console.log(`发送请求到高德地图: ${apiUrl.toString()}`);
  
  try {
    const response = await fetch(apiUrl.toString());
    
    if (!response.ok) {
      console.error(`高德地图API请求失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({ 
        error: `API请求失败: ${response.status} ${response.statusText}` 
      });
    }
    
    const data = await response.json();
    console.log(`步行路线规划响应: status=${data.status}, info=${data.info}`);
    
    res.json(data);
  } catch (error) {
    console.error('高德地图API请求错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 高德地图API代理 - 公交路线规划
app.get('/amap/maps/direction_transit_integrated', async (req, res) => {
  const { origin, destination, city, cityd } = req.query;
  const key = '4449ac26963227ad33708de521f024c5';
  
  console.log(`公交路线规划请求: 起点=${origin}, 终点=${destination}, 出发城市=${city || '上海'}, 到达城市=${cityd || city || '上海'}`);
  
  const apiUrl = new URL('https://restapi.amap.com/v3/direction/transit/integrated');
  apiUrl.searchParams.set('key', key);
  apiUrl.searchParams.set('origin', origin);
  apiUrl.searchParams.set('destination', destination);
  apiUrl.searchParams.set('city', city || '上海');
  apiUrl.searchParams.set('cityd', cityd || city || '上海');
  apiUrl.searchParams.set('extensions', 'all');
  
  console.log(`发送请求到高德地图: ${apiUrl.toString()}`);
  
  try {
    const response = await fetch(apiUrl.toString());
    
    if (!response.ok) {
      console.error(`高德地图API请求失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({ 
        error: `API请求失败: ${response.status} ${response.statusText}` 
      });
    }
    
    const data = await response.json();
    console.log(`公交路线规划响应: status=${data.status}, info=${data.info}`);
    
    res.json(data);
  } catch (error) {
    console.error('高德地图API请求错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 高德地图API代理 - 骑行路线规划
app.get('/amap/maps/bicycling', async (req, res) => {
  const { origin, destination } = req.query;
  const key = '4449ac26963227ad33708de521f024c5';
  
  console.log(`骑行路线规划请求: 起点=${origin}, 终点=${destination}`);
  
  const apiUrl = new URL('https://restapi.amap.com/v4/direction/bicycling');
  apiUrl.searchParams.set('key', key);
  apiUrl.searchParams.set('origin', origin);
  apiUrl.searchParams.set('destination', destination);
  
  console.log(`发送请求到高德地图: ${apiUrl.toString()}`);
  
  try {
    const response = await fetch(apiUrl.toString());
    
    if (!response.ok) {
      console.error(`高德地图API请求失败: ${response.status} ${response.statusText}`);
      return res.status(response.status).json({ 
        error: `API请求失败: ${response.status} ${response.statusText}` 
      });
    }
    
    const data = await response.json();
    console.log(`骑行路线规划响应: status=${data.status}, info=${data.info || data.errcode || '未知状态'}`);
    
    res.json(data);
  } catch (error) {
    console.error('高德地图API请求错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 辅助函数：发起高德地图API请求
function fetchAMapAPI(url) {
  return new Promise((resolve, reject) => {
    const client = url.startsWith('https') ? https : http;
    
    const request = client.get(url, (resp) => {
      // 检查HTTP状态码
      if (resp.statusCode < 200 || resp.statusCode >= 300) {
        return reject(new Error(`HTTP状态码错误: ${resp.statusCode}`));
      }
      
      // 检查内容类型，确保是JSON
      const contentType = resp.headers['content-type'];
      if (!contentType || !contentType.includes('application/json')) {
        console.warn(`警告：响应内容类型不是JSON: ${contentType}`);
      }
      
      let data = '';
      
      resp.on('data', (chunk) => {
        data += chunk;
      });
      
      resp.on('end', () => {
        try {
          // 尝试解析JSON数据
          let parsedData;
          try {
            parsedData = JSON.parse(data);
          } catch (parseError) {
            console.error('无法解析响应为JSON:', data.substring(0, 200) + '...');
            return reject(new Error(`解析JSON响应失败: ${parseError.message}`));
          }
          
          // 检查高德地图API的错误响应
          if (parsedData.status && parsedData.status !== '1') {
            console.error('高德地图API返回错误:', parsedData);
            return reject(new Error(`高德地图API错误: ${parsedData.info || '未知错误'}`));
          }
          
          resolve(parsedData);
        } catch (error) {
          console.error('处理响应时出错:', error);
          reject(new Error(`处理响应失败: ${error.message}`));
        }
      });
    });
    
    // 设置请求超时
    request.setTimeout(10000, () => {
      request.abort();
      reject(new Error('请求超时'));
    });
    
    request.on('error', (error) => {
      console.error('请求出错:', error);
      reject(new Error(`请求失败: ${error.message}`));
    });
  });
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`);
  console.log(`数据库配置: ${JSON.stringify({
    host: dbConfig.host,
    port: dbConfig.port,
    user: dbConfig.user,
    database: dbConfig.database
  })}`);
}); 